package com.course.server.service;


import com.course.server.domain.Section;
import com.course.server.domain.SectionExample;
import com.course.server.dto.SectionDto;
import com.course.server.dto.SectionPageDto;
import com.course.server.mapper.SectionMapper;
import com.course.server.utils.CopyUtil;
import com.course.server.utils.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.beans.Transient;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * 〈一句话功能简述>
 * 〈测试〉
 *
 * @Author metype
 * @Create 2021/5/26
 * @Since 1.0.0
 */
@Service
public class SectionService {

    @Autowired
    private SectionMapper sectionMapper;
    @Autowired
    private CourseService courseService;

    public void list(SectionPageDto sectionPageDto) {
        PageHelper.startPage(sectionPageDto.getPage(), sectionPageDto.getSize());
        SectionExample sectionExample = new SectionExample();
        SectionExample.Criteria criteria = sectionExample.createCriteria();
        if (StringUtil.isNotEmpty(sectionPageDto.getChapterId()) && StringUtil.isNotEmpty(sectionPageDto.getCourseId())) {
            criteria.andChapterIdEqualTo(sectionPageDto.getChapterId());
            criteria.andCourseIdEqualTo(sectionPageDto.getCourseId());
        }
        sectionExample.setOrderByClause("sort asc");
        List <Section> sectionList = sectionMapper.selectByExample(sectionExample);
        PageInfo <Section> pageInfo = new PageInfo <>(sectionList);
        sectionPageDto.setTotal(pageInfo.getTotal());
        List <SectionDto> sectionDtoList = CopyUtil.copyList(sectionList, SectionDto.class);
        sectionPageDto.setList(sectionDtoList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(SectionDto sectionDto) {
        Section section = CopyUtil.copy(sectionDto, Section.class);
        if (StringUtils.isEmpty(sectionDto.getId())) {
            this.insert(section);
        } else {
            this.update(section);
        }
        courseService.updateTime(section.getCourseId());
    }

    private void insert(Section section) {
        Date now = new Date();
        section.setCreatedAt(now);
        section.setUpdatedAt(now);
        section.setId(UuidUtil.getShortUuid());
        sectionMapper.insert(section);
    }

    private void update(Section section) {
        section.setUpdatedAt(new Date());
        sectionMapper.updateByPrimaryKeySelective(section);
    }

    public int del(String id) {
       return sectionMapper.deleteByPrimaryKey(id);
    }

}